<?php

function writepetlog($filename,$logtxt){
	@$fp = fopen(DISCUZ_ROOT.'./petshop/log/'.$filename,'a');
	@flock($fp, 2);
	@fwrite($fp, $logtxt);
	@fclose($fp);
}

function updatestoragebyid($nums,$storageid){
	global $tablepre,$db;
	if($nums==0){
		$db->query("delete from {$tablepre}wxstorage where id='$storageid'",'UNBUFFERED');
	}else{
		$db->query("update {$tablepre}wxstorage set nums='$nums' where id='$storageid'",'UNBUFFERED');
	}
}

function updatestoragebyitemname($username,$itemname,$nums,$dotag=0){
	global $tablepre,$db;
	$myquery=$db->query_first("select nums from {$tablepre}wxstorage where username='$username' and itemname='$itemname'");
	if($myquery){
		if(($nums+$myquery['nums'])>999 && $dotag==0){
			return 0;
		}else{
			$db->query("update {$tablepre}wxstorage set nums=nums+$nums where username='$username' and itemname='$itemname'",'UNBUFFERED');
			return 1;
		}
	}else{
		$db->query("insert into {$tablepre}wxstorage (username,itemname,nums) values ('$username','$itemname','$nums')");
		return 1;
	}
}


function cnstrlen($string){
	global $charset;
	$length=0;
	for($i=0;$i<strlen($string);$i++){
		$length++;
		if($charset!='utf-8'){
			if(ord($string{$i})>127){
				$i++;
			}
		}else{
			if(ord($string{$i})>=224){
				$i+=2;
			}elseif(ord($string{$i})>=192){
				$i++;
			}
		}	
	}
	return $length;
}

function getcnstrn($string,$length){
	global $charset;
	if(strlen($string)<=$length){
		return $string;
	}else{
		if($charset!='utf-8'){
			for($i=0;$i<$length;$i++){
				if(ord($string{$i})>127){
					$i++;
					if($i==$length){
						$length--;
					}
				}
			}
			return substr($string,0,$length);
		}else{
			for($i=0;$i<$length;$i++){
				if(ord($string{$i})>=224){
					$length++;
					$i+=2;
					if($i==$length){
						$length-=2;
					}
				}elseif(ord($string{$i})>=192){
					$i++;
					if($i==$length){
						$length--;
					}
				}
			}
			return substr($string,0,$length);
		}	
	}
}

function updatepetlevel(&$petdata,$dead=0,$dotag=0){
	global $tablepre,$db;
	$sql='';
	$petlevel=$petdata['mypetlevel'];
	$petjob=$petdata['mypetjob'];
	$petexp=$petdata['mypetexp'];
	$nowpetlevel = ceil(pow (log10 (ceil($petexp / ($petjob * 0.2 + 1))), 3));
	$nowpetlevel=$nowpetlevel?$nowpetlevel:1;
	if($nowpetlevel!=$petlevel){
		$petmaxhp = $petdata['mypetmaxhp'] = $petdata['mypetmaxhp'] + ($nowpetlevel - $petlevel) * 25;
		$petmaxmp = $petdata['mypetmaxmp'] = $petdata['mypetmaxmp'] + ($nowpetlevel - $petlevel) * 2;
		$petdata['mypetlevel']=$nowpetlevel;
		$sql.=",mypetlevel='$nowpetlevel',mypetmaxhp='$petmaxhp',mypetmaxmp='$petmaxmp'";
		if($dead==0){
			$petdata['mypethp'] = $petmaxhp;
			$petdata['mypetmp'] = $petmaxmp;
			$petdata['mypetsp']=5000;
			$sql.=",mypethp='$petmaxhp',mypetsp='5000',mypetmp='$petmaxmp'";
		}else{
			$petdata['mypethp']=0;
		}
	}
	if($dotag==1){
		return $sql;
	}
}
?>